<template>
  <div class="page_padding add_absent">
    <MyNavBar @goback="goback" title="旷工记录" />
    <div class="addabsent">
      <div class="self_info">
        <div class="self_title_bold">基本信息</div>
        <div class="correlation_info">
          <div class="left">部门名称：</div>
          <div class="right">{{ formData.orgName }}</div>
        </div>
        <div class="correlation_info">
          <div class="left">姓名：</div>
          <div class="right info_cell" @click="choosePerson">
            <van-cell :value="formData.userInfo.userName ? formData.userInfo.userName : '请选择'" is-link />
          </div>
        </div>

        <div class="correlation_info">
          <div class="left">旷工开始时间：</div>
          <div class="right info_cell" @click="chooseTimeDuty('0')">
            <van-cell :value="formData.startTime ? formData.startTime.slice(0, -3) : '选择时间'" is-link />
          </div>
        </div>
        <div class="correlation_info">
          <div class="left">旷工结束时间：</div>
          <div class="right info_cell" @click="chooseTimeDuty('1')">
            <van-cell :value="formData.endTime ? formData.endTime.slice(0, -3) : '选择时间'" is-link />
          </div>
        </div>
      </div>

      <!-- 底部提交按钮 -->
      <!-- 底部 -->
      <div class="fead_boot">
        <div class="btn_li" @click="submitOut()">提交</div>
      </div>
    </div>
    <van-popup v-model="showTime" position="bottom">
      <div class="pop_days">
        <van-datetime-picker
          v-model="currentDays"
          type="datetime"
          @cancel="showTime = false"
          @confirm="timeConfirm"
          :min-date="minDate"
          :max-date="maxDate" />
      </div>
    </van-popup>

    <van-popup v-model="personPopupShow" position="bottom" class="wit-popup">
      <van-picker
        cancel-button-text="取消"
        show-toolbar
        :columns="userList"
        value-key="userName"
        @confirm="onConfirmPicker"
        @cancel="personPopupShow = false"
        :default-index="defaultIndex" />
    </van-popup>
  </div>
</template>

<script>
import MyNavBar from '@com/MyNavBar'
import moment from 'moment'
import { getDataPermissions, getNeglectRecordDetail, checkIsOverlap, addNeglectRecord } from '@api/api-attendance.js'
export default {
  name: 'AddAbsent',
  components: {
    MyNavBar,
  },
  data() {
    return {
      moment: moment,
      userInfo: JSON.parse(localStorage.userInfo),
      formData: {
        id: '',
        created: JSON.parse(localStorage.userInfo).userName,
        orgName: JSON.parse(localStorage.userInfo).loginPostInfo.orgName,
        orgId: JSON.parse(localStorage.userInfo).loginPostInfo.orgId,
        startTime: '',
        endTime: '',
        userInfo: {
          userName: '',
          userId: '',
        },
      },
      showTime: false,
      currentDays: new Date(),
      personPopupShow: false,
      timeType: '',
      userList: [],
      defaultIndex: 0,
      minDate: new Date(2023, 0, 1),
      maxDate: '',
    }
  },
  created() {
    const dayNow = moment().format('YYYY-MM-DD')
    const arr = dayNow.split('-')
    this.maxDate = new Date(arr[0], Number(arr[1]) - 1, arr[2], 23, 59, 59)
    if (this.$route.query.id) {
      this.getDetail()
    } else {
      this.getDataPermissions()
    }
  },
  mounted() {},
  methods: {
    goback() {
      this.$router.go(-1)
    },
    // 时间选择
    SEConfirm(value) {
      if (this.timeStatus == '1') {
        this.formData.startTime = moment(value).format('YYYY-MM-DD HH:mm')
      } else if (this.timeStatus == '2') {
        this.formData.endTime = moment(value).format('YYYY-MM-DD HH:mm')
      } else if (this.timeStatus == '3') {
        this.formData.backTime = moment(value).format('YYYY-MM-DD HH:mm')
        if (moment(this.formData.backTime).diff(moment(this.formData.startTime), 'minutes') <= 0) {
          this.$toast.fail('销假时间必须大于请假开始时间')
          this.formData.backTime = ''
          return
        }
      }
    },

    getDataPermissions() {
      getDataPermissions({
        type: '2',
      }).then(res => {
        if (res.status === 200) {
          this.userList = res.data[0].userList
          if (this.$route.query.id) {
            const idx = this.userList.findIndex(item => {
              return item.userId === this.formData.userInfo.userId
            })
            this.defaultIndex = idx
          }
        }
      })
    },
    choosePerson() {
      this.personPopupShow = true
    },
    onConfirmPicker(value) {
      this.formData.userInfo = value
      this.personPopupShow = false
    },
    chooseTimeDuty(type) {
      this.currentDays = new Date()
      this.timeType = type
      if (type === '0') {
        if (this.formData.startTime) {
          this.currentDays = moment(this.formData.startTime).toDate()
        }
      } else {
        if (this.formData.endTime) {
          this.currentDays = moment(this.formData.endTime).toDate()
        }
      }
      this.showTime = true
    },
    timeConfirm(value) {
      if (this.timeType === '0') {
        this.formData.startTime = moment(value).format('YYYY-MM-DD HH:mm:ss')
      } else {
        this.formData.endTime = moment(value).format('YYYY-MM-DD HH:mm:ss')
      }
      this.showTime = false
    },
    submitOut() {
      if (!this.formData.userInfo.userId) {
        return this.$toast.fail('请选择人员')
      }
      if (!this.formData.startTime) {
        return this.$toast.fail('请选择旷工开始时间')
      }
      if (!this.formData.endTime) {
        return this.$toast.fail('请选择旷工结束时间')
      }
      if (moment(this.formData.endTime).diff(moment(this.formData.startTime), 'minutes') <= 0) {
        return this.$toast.fail('旷工开始时间不能小于旷工结束时间')
      }
      checkIsOverlap({ ...this.formData, ...this.formData.userInfo }).then(res => {
        if (res.status === 200) {
          if (res.message === '1') {
            addNeglectRecord({ ...this.formData, ...this.formData.userInfo }).then(res => {
              if (res.status === 200) {
                this.$toast.success('提交成功')
                setTimeout(() => {
                  this.$router.go(-1)
                }, 500)
              }
            })
          } else {
            this.$dialog.alert({
              message: res.message,
              closeOnClickOverlay: true,
            })
          }
        }
      })
    },
    getDetail() {
      getNeglectRecordDetail({
        id: this.$route.query.id,
      }).then(res => {
        if (res.status === 200) {
          const { data } = res
          this.formData.id = data.id
          this.formData.startTime = data.startTime
          this.formData.endTime = data.endTime
          this.formData.orgName = data.orgName
          this.formData.orgId = data.orgId
          this.formData.userInfo = {
            userName: data.userName,
            userId: data.userId,
          }
          this.getDataPermissions()
        }
      })
    },
  },
}
</script>

<style lang="scss" scoped>
.add_absent {
  /deep/ .van-popup {
    position: absolute;
  }
}
.addabsent {
  padding: 16px 12px 60px;
  background-color: #f7f7f7;
  font-size: 13px;
  color: #333333;
  width: 100%;
  height: 100%;
  .self_title_bold {
    // font-size: 14px;
    color: #333333;
    font-weight: bold;
  }
  .self_info {
    width: 100%;
    background-color: #ffffff;
    padding: 10px 20px;
    box-shadow: 0 0 10px 0 rgba(4, 0, 0, 0.15);

    .correlation_info {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 9px 0;
      border-bottom: 1px solid #efefef;
      .left {
        font-size: 13px;
      }
      /deep/.van-cell {
        font-size: 12px;
      }
    }
  }
}
</style>
